package com.cqq.login.controller;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cqq.auth.service.UserService;
import com.cqq.auth.service.bean.LoginInfoBean;
import com.cqq.auth.service.exception.UserLoginException;
import com.cqq.auth.service.exception.UserServiceException;
import com.cqq.auth.shiro.AuthUtil;
import com.cqq.base.filter.FMContext;
import com.cqq.common.core.base.BaseController;
import com.cqq.common.core.bean.MessageBean;
import com.cqq.common.core.constant.SessionConstant;
import com.cqq.common.core.util.MapBuilder;

@Controller
@RequestMapping("/")
public class LoginController extends BaseController {

	public static final int COOKIE_MAX_TIME = 60 * 60 * 24 * 7;

	@Autowired
	private UserService userService;

	@RequestMapping("login")
	@ResponseBody
	public ModelAndView login(HttpServletRequest request) {
		return view("login").addAllObjects(autoFill(request));
	}

	@RequestMapping("doLogin")
	@ResponseBody
	public MessageBean doLogin(LoginInfoBean loginInfo, HttpServletRequest request, HttpServletResponse response) {
		try {
			loginInfo.setIp(super.getIPAddress(request));
			loginInfo.setSystemCode(FMContext.getCurrent().getSystemCode());
			
			this.userService.login(loginInfo);
			AuthUtil.login(loginInfo.getUsername(), loginInfo.getPassword());
			remember(loginInfo.getUsername(), loginInfo.getPassword(), request, response);
			return super.buildMessage(MESSAGE_TYPE_SUCCESS, "用户登录成功");
			//使用U盾验证
			/*int checknum = checkWithUdun(loginInfo.getUsername(),request);
			if(checknum==RESULT_AFTER_CHECK_UDUN_FIVE){				
				this.userService.login(loginInfo);
				AuthUtil.login(loginInfo.getUsername(), loginInfo.getPassword());
				remember(loginInfo.getUsername(), loginInfo.getPassword(), request, response);
				return super.buildMessage(MESSAGE_TYPE_SUCCESS, "用户登录成功");
			}else{
				return super.buildMessage(MESSAGE_TYPE_ERROR, getResultWithCheckNum(checknum));
			}*/
		} catch (UserLoginException e) {
			log.error(e.getMessage(), e);
			return super.buildMessage(MESSAGE_TYPE_ERROR, e.getErrorCode(), e.getErrorMsg());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return super.buildMessage(MESSAGE_TYPE_ERROR, "用户登录错误");
		}
	}

	@RequestMapping("logout")
	@ResponseBody
	public MessageBean logout(HttpServletRequest request, HttpSession session) {
		try {
			this.userService.logout();
			AuthUtil.logout();
			//session.invalidate();
			session = null;
			Cookie[] cookies = request.getCookies();
			if (cookies != null && cookies.length > 0) {
				Cookie cookie = cookies[0];
				cookie.setMaxAge(0);
			}
			return super.buildMessage(MESSAGE_TYPE_SUCCESS, "用户登出成功");
		} catch (UserServiceException e) {
			log.error(e.getMessage(), e);
			return super.buildMessage(MESSAGE_TYPE_ERROR, e.getErrorCode(), e.getErrorMsg());
		}
	}

	/** 自动填充 */
	private Map<String, String> autoFill(HttpServletRequest request) {
		Map<String, String> tokenMap = MapBuilder.newHashMap();
		Cookie cookie = getCookie(request);
		if (null != cookie) {
			String value = cookie.getValue();
			String token = base64Decode(value);
			if (StringUtils.isNotBlank(token)) {
				String[] vals = token.split(",");
				tokenMap.put("username", vals[0]);
				tokenMap.put("password", vals[1]);
			}
		}
		return tokenMap;
	}

	/** 记住密码 */
	private void remember(String username, String password, HttpServletRequest request, HttpServletResponse response) {
		if ("true".equals(request.getParameter("remember"))) {
			String val = username + "," + password;
			String token = base64Encode(val);

			if (null == getCookie(request)) {
				Cookie cookie = new Cookie(SessionConstant.LOGIN_USER, token);
				cookie.setMaxAge(COOKIE_MAX_TIME);
				cookie.setPath("/");
				response.addCookie(cookie);
			} else {
				Cookie cookie = getCookie(request);
				cookie.setMaxAge(COOKIE_MAX_TIME);
				cookie.setValue(token);
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		} else {
			Cookie cookie = getCookie(request);
			if (null != cookie) {
				cookie.setValue(null);
				cookie.setMaxAge(0);
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		}
	}

	/** 获得客户端cookie */
	private Cookie getCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (SessionConstant.LOGIN_USER.equals(cookie.getName())) {
					return cookie;
				}
			}
		}
		return null;
	}

	public static String base64Encode(String target) {
		try {
			if (target == null)
				return null;
			byte[] bytes;
			bytes = target.getBytes(Charsets.UTF_8);
			byte[] result = Base64.encodeBase64(bytes);
			return new String(result);
		} catch (Exception e) {
			return null;
		}
	}

	public static String base64Decode(String target) {
		try {
			if (target == null)
				return null;

			if (!Base64.isBase64(target)) {
				return null;
			}

			byte[] orig = Base64.decodeBase64(target);

			return new String(orig);
		} catch (Exception e) {
			return null;
		}
	}
	
}
